<template>
  <view>
    <!-- 注册弹窗 - 暂时注释掉测试 -->
    <!-- <RegistrationModal 
      :visible="showRegistration" 
      :openId="currentOpenId"
      @close="closeRegistrationModal"
      @register-success="handleRegisterSuccess"
    /> -->
  </view>
</template>

<script>
  import config from './config'
  import { getToken } from '@/utils/auth'
  import { getUserCartList } from '@/api/cart'
  import cartCache from '@/utils/cartCache'
  import browseTracker from '@/utils/browseTracker'
  import { getOpenId, checkUserByOpenId, registerWechatUser, wechatAutoLogin } from '@/api/login'
  import { setToken } from '@/utils/auth'
  // import RegistrationModal from '@/components/registration-modal.vue'

  export default {
    // components: {
    //   RegistrationModal
    // },
    data() {
      return {
        showRegistration: false,
        currentOpenId: '',
        cartUpdateTimer: null
      }
    },
    globalData: {
      config: null
    },
    onLaunch: function() {
      this.initApp()
    },
    onShow: function() {
      // 应用显示时更新购物车角标
      this.updateCartBadge()
      // 恢复浏览时长记录
      browseTracker.resume()
    },
    onHide: function() {
      // 应用隐藏时暂停浏览时长记录
      browseTracker.pause()
    },
    methods: {
      // 初始化应用
      initApp() {
        // 初始化应用配置
        this.initConfig()
        // 检查用户登录状态
        //#ifdef H5
        this.checkLogin()
        //#endif
        
        // 监听登录状态过期事件
        uni.$on('loginExpired', this.handleLoginExpired)
      },
      initConfig() {
        this.globalData.config = config
      },
      checkLogin() {
        // 移除强制登录检查，实现免登功能
        // 用户可以在未登录状态下浏览应用
      },
      
      // 处理登录状态过期
      async handleLoginExpired() {
        
        try {
          // 获取微信OpenID (调试用写死)
          const openId = 'oIzdP402wIHMoUaOTestNew12356789'
          
          // 检查用户是否已绑定
          const checkResult = await checkUserByOpenId({ openId })
          
          if (checkResult.data && checkResult.data.userExists) {
            // 用户已绑定，执行自动登录
            const autoLoginResult = await wechatAutoLogin(openId)
            
            if (autoLoginResult.code === 200) {
              // 保存token和openId
              setToken(autoLoginResult.data.token)
              uni.setStorageSync('openId', openId)
              
              uni.showToast({
                title: '自动登录成功',
                icon: 'success'
              })
              
              // 跳转到首页
              uni.reLaunch({
                url: '/pages/index'
              })
            } else {
              throw new Error(autoLoginResult.msg || '自动登录失败')
            }
          } else {
            // 用户未绑定，显示注册弹窗
            this.showRegistrationModal(openId)
          }
        } catch (error) {
          console.error('免登流程失败:', error)
        }
      },
      
      // 显示注册弹窗
      showRegistrationModal(openId) {
        this.currentOpenId = openId
        this.showRegistration = true
      },
      
      // 关闭注册弹窗
      closeRegistrationModal() {
        this.showRegistration = false
        this.currentOpenId = ''
      },
      
      // 处理注册成功
      handleRegisterSuccess(userInfo) {
        console.log('注册成功，用户信息:', userInfo)
        // TODO: 调用JWT登录接口获取token
        uni.showToast({
          title: '注册并登录成功',
          icon: 'success'
        })
        this.closeRegistrationModal()
      },
      
      // 显示登录过期对话框
      showLoginExpiredDialog() {
        uni.showModal({
          title: '提示',
          content: '登录状态已过期，您可以继续留在页面，或者重新登录',
          showCancel: true,
          cancelText: '继续浏览',
          confirmText: '重新登录',
          success: (res) => {
            if (res.confirm) {
              uni.navigateTo({
                url: '/pages/login'
              })
            }
          }
        })
      },
      // 更新购物车角标（带防抖）
      updateCartBadge() {
        // 清除之前的定时器
        if (this.cartUpdateTimer) {
          clearTimeout(this.cartUpdateTimer)
        }
        
        // 设置防抖定时器
        this.cartUpdateTimer = setTimeout(async () => {
          try {
            const userId = uni.getStorageSync('userId') || 'default'
            let cartCount = 0
            
            // 优先从缓存获取购物车数量
            if (cartCache.isCacheValid(userId)) {
              const cachedData = cartCache.getCartCache(userId)
              if (cachedData && cachedData.length > 0) {
                cartCount = cachedData.reduce((total, item) => total + parseInt(item.quantity || 0), 0)
              }
            } else {
              // 缓存无效时从后端获取（仅在有token时）
              const token = getToken()
              if (token) {
                try {
                  const response = await getUserCartList()
                  if (response.code === 200) {
                    const cartData = response.data || []
                    cartCount = cartData.reduce((total, item) => total + parseInt(item.quantity || 0), 0)
                    // 更新缓存
                    cartCache.setCartCache(userId, cartData)
                  }
                } catch (error) {
                  console.log('获取购物车数据失败，使用本地存储')
                  const localCart = uni.getStorageSync('cartList') || []
                  cartCount = localCart.reduce((total, item) => total + parseInt(item.quantity || 0), 0)
                }
              } else {
                // 未登录时使用本地存储
                const localCart = uni.getStorageSync('cartList') || []
                cartCount = localCart.reduce((total, item) => total + parseInt(item.quantity || 0), 0)
              }
            }
            
            // 更新tabbar角标
            if (cartCount > 0) {
              uni.setTabBarBadge({
                index: 2,
                text: cartCount.toString()
              })
            } else {
              uni.removeTabBarBadge({
                index: 2
              })
            }
          } catch (error) {
            console.error('更新购物车角标失败:', error)
          }
        }, 300) // 300ms防抖延迟
      }
    },
    
    onUnload() {
      // 移除事件监听
      uni.$off('loginExpired', this.handleLoginExpired)
      // 清理定时器
      if (this.cartUpdateTimer) {
        clearTimeout(this.cartUpdateTimer)
        this.cartUpdateTimer = null
      }
    }
  }
</script>

<style lang="scss">
  @import '@/static/scss/index.scss'
</style>
